from django.shortcuts import render
from rest_framework import viewsets  # 视图集模块
from rest_framework.response import Response  # 响应
from .models import *  # 模型类
from .serializers import *  # 所有的序列化器类
from rest_framework.status import HTTP_404_NOT_FOUND,HTTP_201_CREATED,HTTP_204_NO_CONTENT
from rest_framework.decorators import action  # 行为路由装饰器



# Create your views here.
"""
create 创建 list 查询所有  retrieve 查询单条 update 修改 delete 删除
"""

# 视图集
# class StudentsViewSet(viewsets.ViewSet):
    # # 查询所有
    # def list(self, request):
    #     # 查询Student所有的数据
    #     students = Student.objects.all()  # 查询集
    #     # 序列化  查询集==>json
    #     serializer = StudentSerializer(students,many=True)
    #     return Response(serializer.data)
    #
    # def create(self,request):
    #     # 反序列化  json==>模型对象
    #     serializer = StudentSerializer(data=request.data)
    #     # 校验
    #     serializer.is_valid(raise_exception=True)
    #     # 保存
    #     serializer.save()
    #     # 响应
    #     return Response(serializer.data)
    #
    # def retrieve(self,request,pk):  # 加入pk参数，条件 id=?  get
    #     try:
    #         student = Student.objects.get(id=pk)
    #
    #     except Student.DoesNotExist:  # 针对于没查询到，没有模型对象才会抛出的异常
    #         return Response(status=HTTP_404_NOT_FOUND)
    #
    #     serializer = StudentSerializer(student)  # 序列化
    #     return Response(serializer.data)
    #
    #
    # def update(self,request,pk):
    #     try:
    #         student = Student.objects.get(id=pk)
    #
    #     except Student.DoesNotExist:  # 针对于没查询到，没有模型对象才会抛出的异常
    #         return Response(status=HTTP_404_NOT_FOUND)
    #
    #     # 反序列化  json==>模型对象
    #     # student原数据
    #     serializer = StudentSerializer(student,data=request.data)
    #     # 校验
    #     serializer.is_valid(raise_exception=True)
    #     # 保存
    #     serializer.save()
    #     # 响应
    #     return Response(serializer.data)
    #
    # def destory(self,request,pk):
    #     try:
    #         student = Student.objects.get(id=pk)
    #
    #     except Student.DoesNotExist:  # 针对于没查询到，没有模型对象才会抛出的异常
    #         return Response(status=HTTP_404_NOT_FOUND)
    #
    #     # 删除
    #     student.delete()
    #     return Response(status=HTTP_204_NO_CONTENT)

# 学生的视图集
class StudentsViewSet(viewsets.ModelViewSet):
    queryset = Student.objects.filter(is_delete=False)  # 查询集
    serializer_class = StudentSerializer  # 需要使用的序列化器

# 班级的视图集
class ClassesViewSet(viewsets.ModelViewSet):
    queryset = Classes.objects.filter(is_delete=False)  # 查询集
    serializer_class = ClassesSerializer  # 需要使用的序列化器

    # 自定义视图集方法
    @action(methods=['get'],detail=False)  # 访问
    def last(self,request):
        classes = Classes.objects.last()
        return Response(self.get_serializer(classes).data)

